<template>
	<u-upload
		:fileList="fileList"
		:maxCount="1"
		:previewFullImage="previewFullImage"
		@afterRead="afterRead"
		@delete="deletePic"
	>
		<view class="upload-box">
			<u-icon name="plus" color="#86909C" size="22"></u-icon>
			<view>{{ title }}</view>
		</view>
	</u-upload>
</template>

<script>
	import {baseUrl} from '@/utils/api/request.js'
	export default {
		props: {
			title: {
				type: String,
				default: '上传确认书'
			},
			previewFullImage: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				fileList: []
			}
		},
		methods: {
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					const url = result.data ? JSON.parse(result.data.replace('\uFEFF', '')): {}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: result.statusCode == 200 ? 'success' : 'error',
						message: '',
						url: url.data
					}))
					fileListLen++
				}
				this.fileList = this.fileList.filter((it) => it.status == 'success')
				this.$emit('setFile', this.fileList)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/member/app/common/upload', 
						filePath: url,
						name: 'file',
						success: (res) => {
							if(res.statusCode != 200) {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								})
							}
							setTimeout(() => {
								resolve(res)
							}, 1000)
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.$emit('setFile', this.fileList)
			},
		}
	}
</script>

<style scoped lang="scss">
.upload-box {
	width: 160upx;
	height: 160upx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border-radius: 4upx;
	background: #F7F8FA;
	>view {
		font-size: 22upx;
		color: #86909C;
		margin-top: 16upx;
	}
}
</style>